package com.weayer.controller;

import com.weayer.request.PushRequest;
import com.weayer.util.SsePrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 司机端建立连接
 * @author: Weayer
 **/
@RestController
@Slf4j
public class SseController {
    // 存储监听的对象
    public static Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * @Description: 建立连接  http://localhost:9000/driver-client.html
     * @Param: [userId, identity]
     * @return: org.springframework.web.servlet.mvc.method.annotation.SseEmitter
     **/
    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam Long userId, @RequestParam String identity){
        System.out.println("【建立连接】用户ID：" + userId + " 身份类型：" + identity);
        SseEmitter sseEmitter = new SseEmitter(0l);
        String sseMapKey = SsePrefixUtils.generatorSseKey(userId, identity);
        sseEmitterMap.put(sseMapKey, sseEmitter);    // 建立连接时，存储SseEmitter对象
        return sseEmitter;
    }

    /**
     * @Description: 推送消息  http://localhost:9000/push?userId=1&identity=1&content=%E5%B0%8F%E9%B9%8F http://localhost:9000/push?driverId=1&content=weayer
     * @Param: [driverId, content]
     * @return: java.lang.String
     **/
    /**
     * @Description:
     * @Param: [userId, identity, content]
     * @return: java.lang.String
     **/
    @PostMapping("/push")
    public String push(@RequestBody PushRequest pushRequest){
        Long userId = pushRequest.getUserId();
        String identity = pushRequest.getIdentity();
        String content = pushRequest.getContent();
        System.out.println("【推送消息】用户ID：" + userId + " 身份类型：" + identity);
        String sseMapKey = SsePrefixUtils.generatorSseKey(userId, identity);
        try {
            if(sseEmitterMap.containsKey(sseMapKey)){
                sseEmitterMap.get(sseMapKey).send(content);  // 将消息推送给客户端
            }else{
                return "推送失败";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "用户：" + sseMapKey + " 内容：" + content;
    }
    /**
     * @Description: 连接关闭
     * @Param: [driverId]
     * @return: java.lang.String
     **/
    @GetMapping("/close")
    public String close(@RequestParam Long userId, @RequestParam String identity){
        String sseMapKey = SsePrefixUtils.generatorSseKey(userId, identity);
        System.out.println("关闭连接" + sseMapKey);
        if(sseEmitterMap.containsKey(sseMapKey)){
            sseEmitterMap.remove(sseMapKey);
        }
        return "已关闭连接";
    }
}
